package com.soft.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * request工具类.
 */
public class RequestUtil {
	/**
	 * 获得请求路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getRequestPath(HttpServletRequest request) {
		String requestPath = request.getRequestURI() + "?" + request.getQueryString();
		if (request.getQueryString() == null) {
			requestPath = request.getRequestURI();
		}
		if (requestPath.indexOf("&") > -1) {// 去掉其他参数
			requestPath = requestPath.substring(0, requestPath.indexOf("&"));
		}
		if (requestPath.indexOf("OF") > -1) {// 去掉附属参数
			requestPath = requestPath.substring(0, requestPath.indexOf("OF"));
		}
		requestPath = ".." + requestPath.substring(request.getContextPath().length());// 去掉项目路径
		return requestPath;
	}
	
	/**
	 * 获取权限地址.
	 */
	public static String getActionUrl(String url) {
		return url;//.substring(0, url.indexOf("?"));
	}
	
	/**
	 * 跳转页面.
	 */
	public static void forward(String url, String msg, HttpServletRequest request, 
			HttpServletResponse response) {
		try {
			request.setAttribute("msg", msg);
			request.getRequestDispatcher(url).forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 跳转页面.
	 */
	public static void go(String url, String msg, HttpServletRequest request, 
			HttpServletResponse response) {
		try {
			request.setAttribute("msg", msg);
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取已登录的SESSION.
	 */
//	public static SessionInfo getSession(HttpServletRequest request, HttpSession session) {
//		SessionContext myc= SessionContext.getInstance();
//		return myc.getSession(session.getId());
//	}
	/**
	 * 获取参数值.
	 */
	public static String getValue(HttpServletRequest request, String name) {
		if (request.getParameter(name) == null) return null;
		return request.getParameter(name).toString();
	}

	/**
	 * 获取当前登录用户.
	 */
	public static String getUsername() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		return userDetails.getUsername();
	}

	
}
